import axios from "axios";
import router from "@/rooter";
import store from "@/store";
import { ElMessage } from 'element-plus'

// 记录发送请求的数量
let requestNum = 0;

const $axios = axios.create({
   baseURL: "http://localhost:8080/api",
   timeout: 5000
})

// 请求拦截器，添加token到请求头中
$axios.interceptors.request.use(
   config => {
      // 加载动画开始
      store.commit('isLoading', true);
      requestNum++;

      // 配置请求头，携带token
      if (localStorage.getItem("token")) {
         config.headers['authorization'] = localStorage.getItem("token");
      }

      return config;
   }
)

$axios.interceptors.response.use((response) => {
   requestNum--;
   if (requestNum <= 0) {
      // 加载动画关闭
      store.commit('isLoading', false);
   }

   // 服务端响应请求失败信息
   // 主要应用于后端返回Result.error对象
   if (!response.data.success) {

      // 系统异常，后端报错，跳转登录界面
      if (response.data.statusCode === 500) {
         if (localStorage.getItem("token")) {
            localStorage.removeItem("token");
         }
         router.replace("/login");
         return Promise.reject();
      }

      if ('success' in response.data) {
         ElMessage({
            type: "error",
            message: response.data.errMessage,
            duration: 3000,
         });
         return Promise.reject();
      }
   }

   return response;
}, (error) => {
   requestNum--;
   // 此处无后端Result.error封装，使用的是原生response对象
   // 响应码不是2xx或服务器无响应时触发
   // 服务端有响应
   if (error.response) {
      // 登录校验失败，请求被拦截
      if (error.response.status === 401) {
         localStorage.removeItem("token");

         router.replace("/login");

         ElMessage({
            type: "warning",
            message: "请先登录",
            duration: 2000,
         });
         return Promise.reject();
      }
   }

   // 服务端无响应
   ElMessage({
      type: "error",
      message: "服务器异常，正在检修，请稍后重试",
      duration: 3000,
   });

   if (localStorage.getItem("token")) {
      localStorage.removeItem("token");
   }

   router.replace("/login");

   return Promise.reject();
});


export default $axios;